﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Business;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Business;
using AMM.UserControls;

namespace AMM.Forms.Business {
    public partial class FrmCustomerOrder : FrmCustomerOrderBase {

        private int _pageIndex;
        private CustomerOrderSearchModel _searchModel;
        private CustomerOrderProcessor _customerOrderProcessor;
        private List<CustomerOrderViewModel> _customerOrderList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1203"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new CustomerOrderSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new CustomerOrder() { ClassStatus = ClassStatus.Added });
            base.Add();
        }

        protected override void Amend() {
            List<CustomerOrderViewModel> selectedList = this.dgvCustomerOrderList.GetSelectedRows<CustomerOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            CustomerOrder customerOrder = this._customerOrderProcessor.FetchCustomerOrderById(selectedList[0].Key);
            customerOrder.ClassStatus = ClassStatus.Updated;
            if ((AuditStatus)customerOrder.OrderStatus == AuditStatus.Audited) {
                this.ShowInfo("审核的订单不能被修改！");
                return;
            }
            this.ShowEditForm("修改", customerOrder);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<CustomerOrderViewModel> selectedList = this.dgvCustomerOrderList.GetSelectedRows<CustomerOrderViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._customerOrderProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Audit() {
            List<CustomerOrderViewModel> selectedList = this.dgvCustomerOrderList.GetSelectedRows<CustomerOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                string resultMsg = string.Empty;
                CustomerOrder customerOrder = this._customerOrderProcessor.FetchCustomerOrderById(selectedList[0].Key);
                if (customerOrder.OrderStatus == (int)AuditStatus.Audited) {
                    if (this.ShowQuestion("订单已经通过审核，确定将取消审核状态！") == DialogResult.No) { return; }
                    customerOrder.OrderStatus = (int)AuditStatus.Waiting;
                    resultMsg = "取消审核成功";
                }
                else {
                    customerOrder.OrderStatus = (int)AuditStatus.Audited;
                    resultMsg = "审核成功";
                }
                customerOrder.AuditedBy = LoginUserName;
                this._customerOrderProcessor.Audit(customerOrder);
                this.MDIParent.SetStatusInformation(resultMsg);
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Audit();
            });
        }       

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new CustomerOrderSearchModel();
                }
                else {
                    this._searchModel = (CustomerOrderSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindCustomerOrderList();
            });
        }

        #endregion

        public FrmCustomerOrder() {
            InitializeComponent();

            this.dgvCustomerOrderList.DataGridViewModelType = typeof(CustomerOrderViewModel);
            this.dgvCustomerOrderDetailList.DataGridViewModelType = typeof(CustomerOrderDetailsViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            CustomerOrder customerOrder = (CustomerOrder)e.EditModel;
            if (customerOrder.CustomerOrderDetails.Count == 0) {
                this.ShowError("请添加订单明细记录！");
                return false;
            }
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                if (customerOrder.ClassStatus == ClassStatus.Added) {
                    customerOrder.CreatedBy = LoginUserName;
                    this._customerOrderProcessor.Insert(customerOrder);
                }
                else {
                    customerOrder.ModifiedBy = LoginUserName;
                    this._customerOrderProcessor.Update(customerOrder);
                }
                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindCustomerOrderList();
            this.BindCustomerOrderDetailsList(0);
        }

        private void BindCustomerOrderList() {
            this.CreateNewThread(() => {
                this._customerOrderList = this._customerOrderProcessor.FetchCustomerOrderViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvCustomerOrderList.DataSource = new SortableBindingList<CustomerOrderViewModel>(this._customerOrderList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindCustomerOrderDetailsList(int customerId) {
            List<CustomerOrderDetailsViewModel> detailsList = new List<CustomerOrderDetailsViewModel>();
            this.CreateNewThread(() => {
                if (customerId != 0) {
                    detailsList = this._customerOrderProcessor.FetchCustomerOrderDetailsViewModelList(customerId);
                }
            }, () => {
                this.dgvCustomerOrderDetailList.DataSource = new SortableBindingList<CustomerOrderDetailsViewModel>(detailsList);
            });
        }

        private void ShowEditForm(string title, CustomerOrder customerOrder) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                CustomerOrderEditControl editControl = new CustomerOrderEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = customerOrder;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                //FrmEntry.LoadAndRunDialog(this.FormEdit);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmCustomerOrder_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._customerOrderProcessor = new CustomerOrderProcessor(this.pceList.PageSize);
                this._searchModel = new CustomerOrderSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindCustomerOrderList();
        }

        private void dgvCustomerOrderList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvCustomerOrderList.CurrentRow != null) {
                int customerId = (int)this.dgvCustomerOrderList.CurrentRow.Cells["Key"].Value;
                this.BindCustomerOrderDetailsList(customerId);
            }
        }
    }
}
